package com.sgj.watchingyou;

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;

import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
import com.sgj.watchinyou.utils.ActivityUtils;

public class ActivityRecognitionIntentService extends IntentService {

	private int mPrevType = 9999;

	public ActivityRecognitionIntentService() {
		// Set the label for the service's background thread
		super("ActivityRecognitionIntentService");
	}

	/**
	 * Called when a new activity detection update is available.
	 */
	@Override
	protected void onHandleIntent(Intent intent) {
		if (ActivityRecognitionResult.hasResult(intent)) {
			ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
			DetectedActivity mostProbableActivity = result.getMostProbableActivity();
			int confidence = mostProbableActivity.getConfidence();
			int activityType = mostProbableActivity.getType();

			if (activityChanged(activityType) && (confidence >= 50) && activityType != DetectedActivity.UNKNOWN) {
				Intent broadcastIntent = new Intent(ActivityUtils.BROADCAST_ACTIVITY_RECOGNITION);
				broadcastIntent.putExtra("action", getNameFromType(activityType));
				broadcastIntent.putExtra("confidence", confidence);
				LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
			}
		}
	}

	private boolean activityChanged(int currentType) {
		if (mPrevType != currentType) {
			mPrevType = currentType;
			return true;

		} else {
			return false;
		}
	}

	private String getNameFromType(int activityType) {
		switch(activityType) {
		case DetectedActivity.IN_VEHICLE:
			return getResources().getString(R.string.vehicle);
		case DetectedActivity.ON_BICYCLE:
			return getResources().getString(R.string.bicycle);
		case DetectedActivity.ON_FOOT:
			return getResources().getString(R.string.foot);
		case DetectedActivity.STILL:
			return getResources().getString(R.string.still);
		case DetectedActivity.UNKNOWN:
			return "unknown";
		case DetectedActivity.TILTING:
			return getResources().getString(R.string.still);
		}
		return "unknown";
	}
	
}
